//
//  DownloadManagerActor 2.swift
//  TestActorDownload
//
//  Created by 罗万能 on 2025/6/13.
//


//
//  DownloadManager.swift
//  TestActorDownload
//
//  Created by rolodestar on 2025/6/13.
//

//
import Foundation
import SwiftData

actor DownloadManager:ObservableObject {
    private var activeTasks: [UUID: DownloadTask] = [:] // 任务ID: 任务对象
    public static var shared: DownloadManager = DownloadManager()
    
    

    init() {
       
    }
    func checkIsExistTask(id: UUID) -> Bool {
        return activeTasks[id] != nil
    }
    
    /// 添加新下载任务
    func addDownloadTask(id:UUID,url: URL) async throws -> UUID{

        for taskValue in activeTasks.values {
            if taskValue.remoteURL == url {
                return taskValue.id
            }
        }
        let taskId = id
        let task = DownloadTask(id: taskId, remoteURL: url)
        activeTasks[taskId] = task
        
        
        try await task.start() // 开始下载
        return taskId
    }
    /// 添加新下载任务
    func addDownloadTask(model: any DownloadTaskForSwiftDataDelegate) async throws -> UUID{

        for taskValue in activeTasks.values {
            if taskValue.remoteURL == model.remoteURL {
                return taskValue.id
            }
        }
        let taskId = model.id
        let task = DownloadTask(model: model)
        activeTasks[taskId] = task
        
        
        try await task.start() // 开始下载
        return taskId
    }
    func startTask(id: UUID) async throws {
        guard let task = activeTasks[id] else { return }
        try await task.start()
    }
        
//    /// 添加新下载任务
//    func addDownloadTask(url: URL) async throws -> UUID{
//
//        for taskValue in activeTasks.values {
//            if taskValue.remoteURL == url {
//                return taskValue.id
//            }
//        }
//        let taskId = UUID()
//        let task = DownloadTask(id: taskId, remoteURL: url)
//        activeTasks[taskId] = task
//        
//        
//        try await task.start() // 开始下载
//        return taskId
//    }
    func addDownloadTask(task: DownloadTask) async throws -> UUID{
        for taskValue in activeTasks.values {
            if taskValue == task {
                return taskValue.id
            }
        }
        activeTasks[task.id] = task
        try await task.start() // 开始下载
        return task.id
    }
    
    /// 暂停任务（保存断点）
    func pauseTask(id: UUID) async {
        guard let task = activeTasks[id] else { return }
        await task.pause()
        
    }
    
    
    //MARK: 如果不是当前打开程序建立的model,如果采用恢复，则不能恢复，因为actor中没有保存有当前model,待改进
    /// 恢复任务（断点续传）
    func resumeTask(id: UUID) async throws {
        guard let task = activeTasks[id] else { return }
        try await task.resume()
        
        
    }
//
//    func updateTaskStatus(id: String, localPath: String){
//        //        activeTasks[id]
//        
//        if let model =  fetchModel(id: id){
//            
//            viewThread(at: "manager func updateTaskStatus")
//            
//            model.localPath = localPath
//            try! modelContext.save()
//            
//        }
//        
//        
//    }
//    @MainActor
//    func updateTaskProcess(id: String, process: Double){
//        //        activeTasks[id]
//        
//        if let model =  fetchModel(id: id){
//            
//            viewThread(at: "manager func updateTaskProcess")
//            
//            model.currentProcess = process
//            try! modelContext.save()
//            
//        }
//        
//        
//    }
    
//   @MainActor public func fetchModel(id: String) -> DownloadDataModel? {
//        
//        let descriptor = FetchDescriptor<DownloadDataModel>(predicate: #Predicate { $0.id == id })
//        return try? modelContext.fetch(descriptor).first
//    }
}

func viewThread(at : String){
    print("at \(at),\(Thread.current)")
}
